﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CoyoEden.Models;
using CoyoEden.Web.Data;
using CoyoEden.Web;
using CoyoEden.Web.Controls;
using Vivasky.Core.Infrastructure;

namespace CoyoEden.Web.Controller
{
	public class TopicController:ControllerBase
	{
		/// <summary>
		/// select a single record
		/// </summary>
		public static Topic Single(Dictionary<string, string> Params, out FeedbackData msg)
		{
			msg = new FeedbackData();
			var user = Params["user"];
			var id = Convert.ToInt32(Params["id"]);
			Topic tempObj = null;
			try
			{
				if (id < 0)
				{
					tempObj = new Topic();
				}
				else
				{
					tempObj = Topic.GetTopic(id.ToString());
					if (tempObj == null)
					{
						msg.Body = string.Format("<h3>无法获取此主题(编号:{0})的信息.</h3>", id);
					}
				}
			}
			catch (Exception ex)
			{
				ResolveException(ex, out msg);
			}
			return tempObj;
		}
		public static Topic Update(List<NameValuePair<string, string>> Params, out FeedbackData msg)
		{
			msg = new FeedbackData();
			try
			{
				//need validate user?
				var user = Params.Find(item => item.name == "user");

				var id = Convert.ToInt32(Params.Find(item => item.name == "itemId").value);
				Topic tempObj = null;
				if (id <= 0)
				{
					tempObj = new Topic();
				}
				else
				{
					tempObj = Topic.Topics.Find(c => c.Id == id);
				}
				tempObj.Title = Params.Find(item => item.name == "itemTitle").value;
				tempObj.Content= Params.Find(item => item.name == "itemContent").value;
				tempObj.Description = (tempObj.Content.Length>30)?tempObj.Content.Substring(0, 30):tempObj.Content;
				//Author profile
				SimpleAuthorProfile profile = new SimpleAuthorProfile();
				profile.Ip = Params.Find(item => item.name == "itemIP").value;
				profile.Email = Params.Find(item => item.name == "itemEMail").value;
				profile.Name = Params.Find(item => item.name == "itemAuthor").value;
				profile.NickName = profile.Name;
				profile.Website = "";
				tempObj.AuthorProfile = profile;

				tempObj.Icon = "";
				tempObj.IsApproved = !PortalSettings.Instance.EnableCommentsModeration;//Todo:topic's approving.
				if (GetCurrentUser().Identity.IsAuthenticated) {
					tempObj.IsApproved = true;
				}

				//topic's community
				var communityID = Params.Find(item => item.name == "itemCommunityID").value;
				tempObj.Communities.Add(Community.GetCommunity(Convert.ToInt32(communityID)));

				tempObj.Save(out msg);
				return tempObj;
			}
			catch (Exception ex)
			{
				ResolveException(ex, out msg);
				return null;
			}
		}
		public static void Delete(Dictionary<string, string> Params, out FeedbackData msg)
		{
			msg = new FeedbackData();
			try
			{
				var key= Params["id"];
				//delete topic
				Topic item = Topic.GetTopic(key);
				item.Delete();
				item.Save();
			}
			catch (Exception ex)
			{
				ResolveException(ex, out msg);
			}
		}
		public static void SelectTopics(Dictionary<string, string> Params, out FeedbackData msg)
		{
			msg = new FeedbackData();
			var currentPage = Convert.ToInt32(Params["CPage"]);
			var rowPerPage = Convert.ToInt32(Params["RPPage"]);
			var communityID = Convert.ToInt32(Params["CommunityID"]);
			var itemViewPath=Params["ViewPath"];
			//Do page
			var allItems = Topic.GetTopicsByCommunity(communityID);
			var user = GetCurrentUser();
			if (!user.IsInRole("administrators"))
			{
				allItems = allItems.FindAll(item=>item.IsApproved==true);//Only show approved topics
			}

			SimplePager pager = new SimplePager();
			List<Topic> items = null;
			if (allItems != null && allItems.Count > 0)
			{
				pager.PagedList<Topic>(allItems, rowPerPage, currentPage, out items);
				//Return first record's id!!.For the purpose of locating the latest record
				msg.Context.Add("TopItemID", items[0].Id);
				//Load Page view
				ViewManager<SimplePagerViewBase> viewObj = new ViewManager<SimplePagerViewBase>("~/Views/SimplePager.ascx");
				viewObj.Control.Pager = pager;
				msg.Context.Add("PagerHtml", viewObj.Render());
				msg.Context.Add("HasItems",true);
			}
			else {
				msg.Context.Add("HasItems",false);
			}




			//Load ITEM view
			ViewManager<CommunityViewBase> itemView = new ViewManager<CommunityViewBase>(itemViewPath);
			itemView.Control.TheCommunity = Community.GetCommunity(communityID);
			itemView.Control.TopicsShow = items;
			
			msg.Context.Add("TopicListHtml", itemView.Render());

			msg.Context.Add("Pager", pager);
			
		}
		public static void ApproveTopic(Dictionary<string, string> Params, out FeedbackData msg) {
			msg = new FeedbackData();
			var itemID=Params["TopicID"];
			var item = Topic.GetTopic(itemID);
			item.IsApproved = true;
			item.Save(out msg);
		}
		public static void UpdateTags(Dictionary<string, string> Params, out FeedbackData msg) {
			msg = new FeedbackData();
			var itemID=Params["id"];
			var tags=Params["tags"];
			var topicViewPath=Params["TopicViewPath"];
			var tagsArray = tags.Split(',');
			var item = Topic.GetTopic(itemID);
			item.Tags.Clear();

			tagsArray.ToList().ForEach(obj => {
				obj = obj.Trim().ToLowerInvariant();
				if (!string.IsNullOrEmpty(obj)) {
					item.Tags.Add(obj);
				}
			});

			item.Save(out msg);

			//render a new topic view
			if (msg.IsOk) {
				ViewManager<TopicViewBase> view = new ViewManager<TopicViewBase>(topicViewPath);
				view.Control.TheTopic = item;
				view.Control.ShowAdminLink = false;
				msg.Context.Add("TopicViewHtml",view.Render());
			}
			
		}
		public static void RemoveComment(Dictionary<string,string> Params,out FeedbackData msg) {
			msg = new FeedbackData();
			var itemId=Params["id"];
			var topicID=Params["TopicID"];

			var topic = Topic.GetTopic(topicID);
			var item = topic.Comments.Find(obj=>obj.Id.ToString()==itemId);
			try
			{
				topic.RemoveComment(item);
			}
			catch (Exception ex) {
				ResolveException(ex, out msg);
			}
		}
		public static void AddComment(List<NameValuePair<string, string>> Params, out FeedbackData msg)
		{
			msg = new FeedbackData();
			Comment item = new Comment();
			item.Id = -1;
			item.Author = Params.Find(obj => obj.name == "itemAuthor").value;
			item.Content = string.Format("{0}<br/>{1}",Params.Find(obj => obj.name == "itemTitle").value,Params.Find(obj => obj.name == "itemContent").value);
			item.Country = "";
			item.Email = Params.Find(obj => obj.name == "itemEMail").value;
			item.IP = Params.Find(obj => obj.name == "itemIP").value;
			item.IsApproved = !PortalSettings.Instance.EnableCommentsModeration;
			item.DateCreated = DateTime.Now;

			if (GetCurrentUser().Identity.IsAuthenticated) {
				item.IsApproved = true;
			}

			item.Website =Utils.AbsoluteWebRoot;//TODO: website of topic comment's author

			var topicID = Params.Find(obj => obj.name == "itemTopicID").value;
			var topic = Topic.GetTopic(topicID);
			try
			{
				topic.AddComment(item);
			}
			catch (Exception ex) {
				ResolveException(ex, out msg);
			}
		}
		public static void SelectComments(Dictionary<string,string> Params,out FeedbackData msg) {
			msg = new FeedbackData();
			var currentPage = Convert.ToInt32(Params["CPage"]);
			var rowPerPage = Convert.ToInt32(Params["RPPage"]);
			var topicID = Params["TopicID"];
			var itemViewPath = Params["ViewPath"];
			var topic=Topic.GetTopic(topicID);
			//Do page
			var allItems = topic.Comments;
			var user = GetCurrentUser();
			if (!user.IsInRole("administrators"))
			{
				allItems =topic.ApprovedComments;//Only show approved topics
			}

			allItems=allItems.OrderByDescending(obj => obj.DateCreated).ToList();
			SimplePager pager = new SimplePager();
			List<Comment> items = null;
			if (allItems != null && allItems.Count > 0)
			{
				pager.PagedList<Comment>(allItems, rowPerPage, currentPage, out items);
				//Return first record's id!!.For the purpose of locating the latest record
				msg.Context.Add("TopItemID", items[0].Id);
				msg.Context.Add("CommentsNum",allItems.Count);
			}
			else {
				pager.CurrentPage = currentPage;
				pager.RowPerPage = rowPerPage;
				pager.RowTotal = 0;
				pager.PageTotal = 0;
				pager.Tip = "没有任何记录可以显示";
			}


			//Load Pager view
			ViewManager<SimplePagerViewBase> viewObj = new ViewManager<SimplePagerViewBase>("~/Views/SimplePager.ascx");
			viewObj.Control.Pager = pager;
			msg.Context.Add("PagerHtml", viewObj.Render());

			//Load Comment's ITEM view of a topic
			ViewManager<TopicViewBase> itemView = new ViewManager<TopicViewBase>(itemViewPath);
			itemView.Control.TheTopic= topic;
			itemView.Control.CommentsShow= items;

			msg.Context.Add("CommentListHtml", itemView.Render());

			msg.Context.Add("Pager", pager);
		}
	}
}
